package cn.db.crawl.data.pipeline;

import cn.db.crawl.data.entity.BingImage;
import cn.db.crawl.data.mapper.BingImageMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.time.LocalDate;

/**
 * @author：zooooooooy
 * @date: 2022/12/1 - 19:05
 */
@Component
@AllArgsConstructor
public class BingImagePipeline implements Pipeline {

    private BingImageMapper bingImageMapper;

    @Override
    public void process(ResultItems resultItems, Task task) {

        if (!resultItems.isSkip()) {
            BingImage bingImage = resultItems.get("bingImage");
            // 判断是否存在
            BingImage localBingImage = bingImageMapper.selectOne(new LambdaQueryWrapper<BingImage>()
                    .eq(BingImage::getImageDate, LocalDate.now())
            );
            if (localBingImage != null) {
                // 存在更新
                bingImage.setId(localBingImage.getId());
                bingImageMapper.updateById(bingImage);
            } else {
                // 不存在则插入
                bingImageMapper.insert(bingImage);
            }
        }

    }
}
